package weiyao.xinxidasai.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import weiyao.xinxidasai.DTO.Result;
import weiyao.xinxidasai.pojo.Users;
import weiyao.xinxidasai.service.UserService;

import javax.validation.Valid;
import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public Result register(@Valid @RequestBody Users user) {

        System.out.println("securityLevel = " + user.getSecurityLevel());
        System.out.println("有人注册");
        if (userService.countByUsername(user.getUsername()) > 0) {
            return Result.fail("用户名已经被注册") ;
        }
        userService.addUser(user);
        return Result.ok("注册成功");
    }

    @PostMapping("/login")
    public Result login(@Valid @RequestBody Users user) {
        System.out.println("有人登录");
       //发放token（登录用）等直接交给服务层实现
        return userService.login(user);
    }

    //通过api生成私钥
    @PostMapping("/FaceToken")
    public Result FaceToken(@RequestParam("file") MultipartFile file) throws IOException {
        String contentType = file.getContentType();
        if (!"image/jpeg".equals(contentType) && !"image/png".equals(contentType)) {
            return Result.fail("只支持 JPG/PNG 格式图片");
        }
        if (file.isEmpty()) {
            return Result.fail("不能上传空文件");
        }
        if (file.getSize()>1048576*10){
            return Result.fail("文件图片内容过大");
        }
        return (userService.FaceToken(file));
    }


}
